//
//  SLComposeView.swift
//  Sina15
//
//  Created by 盼 on 16/4/20.
//  Copyright © 2016年 pan. All rights reserved.
//

import UIKit

class SLComposeView: UIView {
    
    var target: UIViewController?
    
    func show(target: UIViewController){
        
        self.target = target
        
        target.view.addSubview(self)
    }
    
    override init(frame: CGRect) {
        
        let rect = UIScreen.mainScreen().bounds
        
        super.init(frame: rect)
        
        backgroundColor = UIColor.whiteColor()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK:设置UI界面
    func setupUI(){
        addSubview(backgroundImageView)
        addSubview(sloganView)
        
        backgroundImageView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.bottom.equalTo(self)
        }
        
        sloganView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
        }
        
        //添加按钮
        addButtons()
    }
    
    //MARK:按钮的点击事件
    @objc private func btnDidClick(button: SLComposeButton) {
        
        for btn in buttonArr {
            var scale:CGFloat = 0
            if button == btn {
                scale = 2.0
            }else{
                scale = 0.1
            }
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                btn.alpha = 0
                btn.transform = CGAffineTransformMakeScale(scale, scale)
                }, completion: { (_) -> Void in
                    
                    self.removeFromSuperview()
            })
            
        }
        //获取到要跳转的控制器
        guard let className = button.composeItem?.target else {
            print("没有目标控制器")
            
            return
        }
        
        let classType = NSClassFromString(className) as! UIViewController.Type
        
        //创建控制器
        let vc = classType.init()
        
        let nav = UINavigationController(rootViewController: vc)
        
        //跳转到目标控制器，只有控制器才可以跳转
        target?.presentViewController(nav, animated: true, completion: nil)
    }
    
    //MARK:添加按钮
    private func addButtons(){
        
        let btnY:CGFloat = 0
        let btnW:CGFloat = 80
        let btnH:CGFloat = 110
        let margin:CGFloat = (UIScreen.mainScreen().bounds.width - (3 * btnW)) / 4
        
        for i in 0 ..< composeInfos.count {
            
            let btn = SLComposeButton()
            //设置模型数据
            btn.composeItem = composeInfos[i]
            
            btn.titleLabel?.textAlignment = .Center
            btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
            btn.titleLabel?.font = UIFont.systemFontOfSize(15)
            
            //设置子控件在父控件中的位置，要设置frame，bounds是相对于自身的约束
            let rect = CGRect(x: 0, y: btnY, width: btnW, height: btnH)
            
            let offsetY = (btnH + margin) * CGFloat(i / 3) + screenHeight
            let offsetX = margin + (margin + btnW) * CGFloat(i % 3)
            
            btn.frame = CGRectOffset(rect, offsetX, offsetY)
            
            //给按钮添加点击事件
            btn.addTarget(self, action: "btnDidClick:", forControlEvents: .TouchUpInside)
            
            buttonArr.append(btn)
            
            addSubview(btn)
        }
    }
    
    //MARK:点击屏幕移除composeView
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (index,button) in buttonArr.reverse().enumerate() {
            
            animation(button, index: index)
        }
    }
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        //遍历数组依次实现动画效果
        for (index,button) in buttonArr.enumerate() {

            animation(button, index: index, isUp: true)
        }
    }
    
    private func animation(button: SLComposeButton,index: Int,isUp: Bool = false){
        
        UIView.animateWithDuration(0.5, delay: Double(index)*0.05, usingSpringWithDamping: 0.7, initialSpringVelocity: 5, options: [], animations: { () -> Void in
            
            //修改按钮的中心点
            button.center = CGPoint(x: button.center.x, y: button.center.y + (isUp ? -350 : 350))
            
            }, completion: { (_) -> Void in
                
                if !isUp {
                    self.removeFromSuperview()
                }
        })
    }
    
    private lazy var backgroundImageView = UIImageView(image: UIImage.screenShot().applyLightEffect()!)
    
    private lazy var sloganView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    //数组按钮
    private lazy var buttonArr = [SLComposeButton]()
    
    //模型数据
    private lazy var composeInfos:[SLComposeItem] = {
       
        let filePath = NSBundle.mainBundle().pathForResource("composeButton.plist", ofType: nil)!
        
        let items = NSArray(contentsOfFile: filePath) as! [[String: String]]
        
        var tempArr = [SLComposeItem]()
        
        //遍历数组字典转模型
        for item in items {
            
            let composeItem = SLComposeItem(dict: item)
            
            tempArr.append(composeItem)
        }
        return tempArr
    }()
    
    
}
